﻿//--------------------------------------------------------------------------
// 
//  Copyright (c) Chili Software.  All rights reserved. 
// 
//  File: OleDbStorage.cs
//
//  Description: Provides a storage class for OLEDB.
// 
//--------------------------------------------------------------------------

using System;
using System.Reflection;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;
using Chili.Opf3.Query;
using Chili.Opf3.Query.OPathParser;

namespace Chili.Opf3.Storages.OleDb
{
	/// <summary>Storage class that encapsulates a pyhsical OleDb database.</summary>
	/// <remarks>
	/// 	<para>This class encapsulates a physical OleDb database. It is used to access to
	///     an Oracle database that is installed somewhere on your or on a remote machine. The storage
	///     implements the basic interfaces, such as
	///     <see cref="Opf3.Storages.IStorage">IStorage</see> for the basic storage IO
	///     functinality and
	///     <see cref="Opf3.Storages.ITransactionStorage">ITransactionStorage</see> for the
	///     transaction management.</para>
	/// 	<para><b>Attention:</b> You should not access the methods of the storage directly
	///     but instead register the storage with your instances of the
	///     <see cref="Opf3.ObjectContext">ObjectContext</see>. The
	///     <see cref="Opf3.ObjectContext">ObjectContext</see> accesses the methods internally
	///     to get the objects from the storage.</para>
	/// </remarks>
	/// <example>
	/// The following example shows how you should use the OleDb storage in your 
	/// applications.
	/// <code lang="CS">
	/// // ... Other code
	/// 
	/// // Creates a new ObjectContext that uses an OleDb database as storage.
	/// // You should only pass an instance of the storage to your ObjectContext.
	/// // That's it! Nothing more. The methods of the storage are accessed
	/// // by the context internally.
	/// ObjectContext context = new ObjectContext(
	///		new OleDbStorage("... some ConnectionString ..."));
	/// 
	/// // ... Other code
	/// </code>
	/// </example>
	public class OleDbStorage : SqlStorageBase
	{
		private const string _constraintError = "3316";
		private const string _foreignKeyViolation = "3201";
		private const string _primaryKeyViolation = "3022";
		private const string _indexViolation = "2601";

		/// <summary>
		/// Creates a new instance of the <see cref="OleDbStorage">OleDbStorage
		/// Class</see>.
		/// </summary>
		/// <param name="connectionString">
		/// Specifies a string that contains the information (for ADO.NET) to connect to
		/// storage.
		/// </param>
		public OleDbStorage(string connectionString) : base(connectionString)
		{
			this.StorageCommandBuilders.Add(new OleDbCommandBuilder());
			this.StorageCommandBuilders.Add(new SqlQueryCommandBuilder());
		}

		#region Overridden Members

		/// <summary>
		/// Executes a command on the storage that does not expect any results. It the method
		/// returns an argument it is used by the framework to set the
		/// <see cref="Opf3.FieldAttribute.AutoNumber">AutoNumber</see> property of the persistent
		/// object.
		/// </summary>
		/// <param name="query">
		/// 	<see cref="Opf3.Query.IQuery">IQuery</see> that is compiled and executed on the
		/// storage.
		/// </param>
		/// <exception cref="Opf3.Storages.StorageConstraintException">A constraint of the storage 
		/// has been violated.</exception>
		/// <exception cref="Opf3.Storages.ForeignKeyViolationException">A foreign key in the storage 
		/// has been violated.</exception>
		/// <exception cref="Opf3.Storages.PrimaryKeyViolationException">A duplicate primary key 
		/// is inserted in the storage.</exception>
		/// <exception cref="Opf3.Storages.PrimaryKeyViolationException">An index has been violated.</exception>
		/// <exception cref="Opf3.Storages.StorageException">Any other unexpected storage exception.</exception>
		public override object ExecuteCommand(IQuery query)
		{
			try
			{
				return base.ExecuteCommand(query);
			}
			catch (OleDbException ex)
			{
				if (ex.Errors[0].SQLState == _constraintError)
					throw new StorageConstraintException(ex.Message, ex, query);
				else if (ex.Errors[0].SQLState == _foreignKeyViolation)
					throw new ForeignKeyViolationException(ex.Message, ex, query);
				else if (ex.Errors[0].SQLState == _primaryKeyViolation)
					throw new PrimaryKeyViolationException(ex.Message, ex, query);
				else if (ex.Errors[0].SQLState == _indexViolation)
					throw new IndexViolationException(ex.Message, ex, query);
				else
					throw new StorageException(ex.Message, ex, query);
			}
		}

		/// <summary>
		/// Executes and compiles the <see cref="Opf3.Query.IQuery">IQuery</see> and returns
		/// an <see cref="Opf3.ObjectReader{T}">ObjectReader</see> with the resultsset.
		/// </summary>
		/// <param name="context">
		/// 	<see cref="Opf3.ObjectContext">ObjectContext</see> that is connected with the
		/// <see cref="Opf3.ObjectReader{T}">ObjectReader</see>.
		/// </param>
		/// <param name="query">
		/// 	<see cref="Opf3.Query.IQuery">IQuery</see> that is compiled and executed on the
		/// storage.
		/// </param>
		/// <exception cref="Opf3.Storages.StorageException">An unexpected storage exception has happened.</exception>
		public override ObjectReader<T> ExecuteReader<T>(ObjectContext context, IQuery query)
		{
			try
			{
				return base.ExecuteReader<T>(context, query);
			}
			catch (OleDbException ex)
			{
				throw new StorageException(ex.Message, ex, query);
			}
		}

		/// <summary>Creates a new storage dependent connection object.</summary>
		/// <returns>Returns an instance of a storage dependent connection object.</returns>
		public override IDbConnection CreateConnection()
		{
			// Create the connection and open it.
			OleDbConnection connection = new OleDbConnection(this.ConnectionString);
			connection.Open();
			return connection;
		}

		/// <summary>Creates a new storage dependent command object.</summary>
		/// <returns>Returns an instance of a storage dependent command object.</returns>
		public override IDbCommand CreateCommand()
		{
			return new OleDbCommand();
		}

		/// <summary>Creates and populates a storage dependent parameter with data.</summary>
		/// <returns>
		/// The name of the storage parameter should be set to a valid parameter name (one
		/// that is supported by the storage) while creating the parameter.
		/// </returns>
		/// <param name="index">Index of the storage parameter.</param>
		/// <param name="name">Name of the storage parameter.</param>
		/// <param name="value">Value of the storage parameter.</param>
		/// <param name="type">The type of the value argument. This information is useful if the value is null.</param>
		/// <exception cref="ArgumentNullException">Name is null.</exception>
		public override IDataParameter CreateParameter(int index, ref string name, object value, Type type)
		{
			if (name == null)
				throw new ArgumentNullException("name");

			// Set the name for the parameter.
			name = "?";

			if (value == null)
			{
				OleDbType oleDbType = OleDbType.VarChar;

				// Convert to the sql server type.
				if (type == typeof(int)) oleDbType = OleDbType.Integer;
				else if (type == typeof(short)) oleDbType = OleDbType.SmallInt;
				else if (type == typeof(long)) oleDbType = OleDbType.BigInt;
				else if (type == typeof(string)) oleDbType = OleDbType.VarChar;
				else if (type == typeof(byte[])) oleDbType = OleDbType.VarBinary;
				else if (type == typeof(bool)) oleDbType = OleDbType.Boolean;
				else if (type == typeof(DateTime)) oleDbType = OleDbType.Date;
				else if (type == typeof(decimal)) oleDbType = OleDbType.Currency;
				else if (type == typeof(double)) oleDbType = OleDbType.Double;
				else if (type == typeof(Single)) oleDbType = OleDbType.Single;
				else if (type == typeof(Guid)) oleDbType = OleDbType.IUnknown;
				else if (type == typeof(object)) oleDbType = OleDbType.PropVariant;

				OleDbParameter parameter = new OleDbParameter(name, oleDbType);
				parameter.Value = DBNull.Value;
				return parameter;
			}

			if (value is decimal)
			{
				OleDbParameter parameter = new OleDbParameter(name, OleDbType.Currency);
				parameter.Value = value;
				return parameter;
			}

			if (value is DateTime)
			{
				OleDbParameter parameter = new OleDbParameter(name, OleDbType.Date);
				parameter.Value = value;
				return parameter;
			}

			// Check if the value is null. Convert it then to DBNull.
			return new OleDbParameter(name, value);
		}

		/// <summary>Transforms the parameter to a valid field.</summary>
		/// <returns>Returns a string that represents a valid field name.</returns>
		/// <remarks>
		/// This method returns a field name that is valid for the current storage. For some
		/// storages it is a better choice to start each field name with a '[' and end with a ']'
		/// (Ms Access) - This method could wrap each field name passed with '[]'.
		/// </remarks>
		/// <param name="name">Name for the field that is transformed.</param>
		/// <exception cref="ArgumentNullException">Name is null.</exception>
		public override string GetValidFieldName(string name)
		{
			if (name == null)
				throw new ArgumentNullException("name");

			return string.Format("[{0}]", name);
		}

		/// <summary>
		/// Transforms the name of the entity to a valid entity name.
		/// </summary>
		/// <returns>Returns a string that represents a valid entity name.</returns>
		/// <remarks>
		/// This method returns an entity name that is valid for the current storage. For
		/// some storages it is a better choice to start each entity name with a '[' and end with a
		/// ']' (Ms Access) - This method could wrap each entity name passed with '[]'.
		/// </remarks>
		/// <param name="name">Name of the entity.</param>
		/// <exception cref="ArgumentNullException">Name is null.</exception>
		public override string GetValidEntityName(string name)
		{
			if (name == null)
				throw new ArgumentNullException("name");

			return string.Format("[{0}]", name);
		}

		#endregion
	}
}
